package data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import models.OrderFeedbackModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class OrderFeedbackData {
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "orderFeedbackData";

	private int limit = 20;

	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public OrderFeedbackData() {
		try {
			ObjectifyService.register(OrderFeedbackModel.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}

	public ArrayList<OrderFeedbackModel> list() {
		ArrayList<OrderFeedbackModel> list = new ArrayList<OrderFeedbackModel>();

		int start = (page - 1) * limit;
		Query<OrderFeedbackModel> q = ofy.query(OrderFeedbackModel.class)
				.limit(limit).offset(start);
		for (OrderFeedbackModel geo : q) {
			list.add(geo);
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	public void insert(OrderFeedbackModel obj) {
		if (cache != null) {
			cache.put(prefix + obj.getFeedbackId(), obj);
		}
		ofy.put(obj);
	}

	public void delete(OrderFeedbackModel obj) {
		if (cache != null && cache.containsKey(prefix + obj.getFeedbackId())) {
			cache.remove(prefix + obj.getFeedbackId());
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public OrderFeedbackModel getById(String id) {
		OrderFeedbackModel obj = new OrderFeedbackModel();
		if (cache != null && cache.containsKey(prefix + id)) {
			obj = (OrderFeedbackModel) cache.get(prefix + id);
		} else {
			try {
				obj = ofy.get(new Key<OrderFeedbackModel>(
						OrderFeedbackModel.class, id));
				cache.put(prefix + id, obj);
			} catch (Exception e) {
				obj = null;
			}
		}
		return obj;
	}

	public List<OrderFeedbackModel> getFeedbackByOrderId(String orderId) {
		ArrayList<OrderFeedbackModel> list = new ArrayList<OrderFeedbackModel>();
		try {
			Query<OrderFeedbackModel> q = ofy.query(OrderFeedbackModel.class)
					.filter("orderId", orderId);
			if (q.count() > 0) {
				for (OrderFeedbackModel orderFeedbackModel : q) {
					list.add(orderFeedbackModel);
				}
			}
		} catch (Exception e) {
			list = null;
		}
		return list;
	}

}
